package com.gitee.chili.leisure.core;

import com.gitee.chili.leisure.exception.NettyMessageHandlerException;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;


/**
 * 消息调度类
 */
@Slf4j
public class DefaultMessageReceiver implements MessageReceiver {

    /** 消息注册器 */
    private final MessageHandlerRegistry messageHandlerRegistry;

    public DefaultMessageReceiver(MessageHandlerRegistry messageHandlerRegistry) {
        this.messageHandlerRegistry = messageHandlerRegistry;
    }

    @Override
    public MessageHandlerRegistry getRegistry() {
        return messageHandlerRegistry;
    }

    @Override
    public void onReceive(Packet packet, Channel channel) {

        // 获取消息处理器
        MessageHandler handler = messageHandlerRegistry.getHandler(packet.getCmd());
        try {
            Assert.notNull(handler, "未找到匹配的消息处理器");
            // 开始处理消息
            handler.onHandler(packet, channel);
        } catch (Exception e) {
            log.error("消息处理异常  命令: [ {} ] ", packet.getCmd(), new NettyMessageHandlerException(e));
        }
    }

}
